package com.ljb.http.retrofit.config;

import com.ljb.http.logger.Logger;

import java.io.IOException;
import java.nio.charset.Charset;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

/**
 * 日志拦截器
 * Created by lijianbin on 2016/12/16.
 */
public class LoggingInterceptor implements Interceptor {

    private final String TAG = "RetrofitRequest";

    @Override
    public Response intercept(Chain chain) throws IOException {
        //request请求
        Request request = chain.request();
        String url = request.url().toString();
        String method = request.method();
        long t1 = System.nanoTime();

        //response相应结果
        Response response = chain.proceed(request);
        long t2 = System.nanoTime();

        ResponseBody body = response.body();
        BufferedSource source = body.source();
        source.request(Long.MAX_VALUE); // Buffer the entire body.
        Buffer buffer = source.buffer();
        Charset charset = Charset.defaultCharset();
        MediaType contentType = body.contentType();
        if (contentType != null) {
            charset = contentType.charset(charset);
        }
        String bodyString = buffer.clone().readString(charset);

        Logger.d("请求url地址:" + url + "\n"
                + "请求方式:" + method + "\n"
                + "响应时间:" + (t2 - t1) + "\n"
                + "是否响应成功:" + response.isSuccessful() + "\n"
                + "响应信息:" + response.message() + "\n"
                + "响应码:" + response.code() + "\n"
        );
        Logger.json(bodyString);
        return response;
    }
}
